//
//  SNEquipmentScreenImageView.m
//  project
//
//  Created by 张淋 on 2019/5/15.
//  Copyright © 2019 黄建华. All rights reserved.
//

#import "SNEquipmentScreenImageView.h"

@interface SNEquipmentScreenImageView ()

@end


@implementation SNEquipmentScreenImageView

- (instancetype)init {
    if (self == [super init]) {
        [self initUI];
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame {
    if (self == [super initWithFrame:frame]) {
        [self initUI];
    }
    return self;
}

//118118
- (void)updateImageView {
    float x = [[[[NSUserDefaults standardUserDefaults] objectForKey:@"ScreenViewXy"] objectForKey:@"x"] floatValue] ? [[[[NSUserDefaults standardUserDefaults] objectForKey:@"ScreenViewXy"] objectForKey:@"x"] floatValue] : SCREENMORERENWIDTH;
    float y = [[[[NSUserDefaults standardUserDefaults] objectForKey:@"ScreenViewXy"] objectForKey:@"y"] floatValue] ? [[[[NSUserDefaults standardUserDefaults] objectForKey:@"ScreenViewXy"] objectForKey:@"y"] floatValue] : SCREENMORERENHEIGHT;

    NSString *sss = [NSString stringWithFormat:@"🙂🙂🙂:手环:%@ W:%d H:%d   🙂save x %d y:%d", KK_BLEModel.bleName, KK_BLEModel.bleDeviceWidth, KK_BLEModel.bleDeviceHeight, x, y];

    NSLog(@"🙂🙂🙂>>>>%@", sss);
    LogWrite(nil, sss, nil);
    CGFloat width  = KK_BLEModel.bleDeviceWidth;
    CGFloat height = KK_BLEModel.bleDeviceHeight;
    _backImageView.frame = SNFRAME(screenWidth/2 -width/2, 0, width, height);

    // 1 118
    if (SN_USER.screen_type) {
        UIView *bgView = [[UIView alloc] initWithFrame:SNFRAME(50, 50, 240, 240)];
        bgView.backgroundColor          = [UIColor blackColor];
        bgView.clipsToBounds            = YES;
        bgView.layer.minificationFilter = kCAFilterTrilinear;
//    [self.view addSubview:bgView];

        UIView *bgView2 = [[UIView alloc] initWithFrame:SNFRAME(-20, -10, 240+40, 240+40)];
        bgView2.layer.cornerRadius       = (240+40)/2;
        bgView2.backgroundColor          = [UIColor whiteColor];
        bgView2.layer.minificationFilter = kCAFilterTrilinear;
        [bgView addSubview:bgView2];

        UIGraphicsBeginImageContext(bgView.bounds.size); //currentView 当前的view
        [bgView.layer renderInContext:UIGraphicsGetCurrentContext()];
        UIImage *firstImage = UIGraphicsGetImageFromCurrentImageContext();

        UIGraphicsEndImageContext();
//    UIImageWriteToSavedPhotosAlbum(firstImage, nil, nil, nil);  //保存到相册中
        NSArray *changeArray = [self imageToTransparentArray:firstImage];

        UIImage *image;
        if ([self getDocumentImage]) {
            image = [self getDocumentImage];
        } else {
//         57629(IT106S) 45597（118）
            if (KK_BLEModel.bleAdvID == 57629 || KK_BLEModel.bleAdvID == 59677) {
                image = [UIImage imageNamed:@"银河240240"];
            } else if (KK_BLEModel.bleAdvID == 45597) {// 银
                image = [UIImage imageNamed:@"花瓣240240"];
            } else {
                image = [UIImage imageNamed:@"WechatIMG11"];
            }
            //保存默认图片
//            [self saveImageDocuments:[UIImage imageCompressForSize:image targetSize:CGSizeMake(width, height)]];
        }

        UIImage *image2 = image;
        UIImage *second = [self imageToTransparent:image2 withChange:changeArray];
//    UIImageWriteToSavedPhotosAlbum(second, nil, nil, nil);  //保存到相册中
        _backImageView.image = second;
        _sendImage222 = second;
    } else {
        return;
    }
}

- (void)initUI {
    UIView *stateView = [[UIView alloc] init];

    stateView.frame           = CGRectMake(0, 0, kSCREEN_WIDTH, 20);
    stateView.backgroundColor = BBIGSTATECOLOR;
    [self addSubview:stateView];

    UIView *naView = [[UIView alloc] init];
    naView.frame           = CGRectMake(0, 20+FitSimpleIpx(0, 20), kSCREEN_WIDTH, 44);
    naView.backgroundColor = [UIColor whiteColor];
    [self addSubview:naView];

    UILabel *lable = [[UILabel alloc]initWithFrame:CGRectMake(0, 20+FitSimpleIpx(0, 20), screenWidth, 44)];
    lable.textColor     = [UIColor blackColor];
    lable.font          = SNFONT(17);
    lable.textAlignment = NSTextAlignmentCenter;
    lable.text          = HHH_Text(@"更换壁纸");
    [self addSubview:lable];

    UIImageView *shadowLine = [[UIImageView alloc] init];
    shadowLine.frame = SNFRAME(0, naView.bottom, HHHWIDTH, 2);
    shadowLine.image = [UIImage image:@"lineImage"];
    [self addSubview:shadowLine];

    UIButton *leftButton = [[UIButton alloc] init];
    leftButton.frame = CGRectMake(5, 20+FitSimpleIpx(0, 20), 44, 44);
    [leftButton setImageNormal:@"进入"];
    leftButton.tag = 300;
    [leftButton addTarget:self action:@selector(clickedAction:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:leftButton];

    UIButton *rightButton = [[UIButton alloc] init];
    rightButton.frame = CGRectMake(HHHWIDTH-80-5, 20+FitSimpleIpx(0, 20), 80, 44);
    [rightButton setTitleNormal:HHH_Text(@"保存")];
    rightButton.titleLabel.font = SNFONT(16);
    [rightButton setTitleColorNormal:SNCOLORBLACK];
    rightButton.tag = 400;
    [rightButton addTarget:self action:@selector(clickedAction:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:rightButton];

    // 锁屏功能
    UIView *bgWhite1 = [[UIView alloc] initWithFrame:CGRectMake(0, 15 + naView.bottom, screenWidth, 44)];
    bgWhite1.backgroundColor = SNCOLORWHITE;
    [self addSubview:bgWhite1];

    UIImageView *imagev = [[UIImageView alloc] init];
    imagev.frame = CGRectMake(20, (bgWhite1.height - 23) / 2, 20, 23);
    imagev.image = [UIImage imageNamed:@"ghbz_icon_suo"];
    [bgWhite1 addSubview:imagev];

    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(imagev.right+10, (bgWhite1.height - 20) / 2, 200, 20)];
    label.text          = HHH_Text(@"启用屏保功能");
    label.textAlignment = NSTextAlignmentLeft;
    [bgWhite1 addSubview:label];

    _openSwitch = [[ZJSwitch alloc] initWithFrame:CGRectMake(screenWidth- 70, (bgWhite1.height - 22) / 2, 50, 22)];
    [_openSwitch addTarget:self action:@selector(clickedAction:) forControlEvents:UIControlEventValueChanged];
    _openSwitch.tag = 999;
    [bgWhite1 addSubview:_openSwitch];

    // 父视图
    _bgView = [[UIView alloc] initWithFrame:(CGRect)CGRectMake(0, bgWhite1.bottom + 5, self.width, self.height - bgWhite1.height - naView.height - stateView.height)];
    [self addSubview:_bgView];
    _bgView.hidden = YES;

    // 屏保
    UIView *bgWhite2 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, screenWidth, 240)];
    bgWhite2.backgroundColor = SNCOLORWHITE;
    [_bgView addSubview:bgWhite2];

    UIImage *image;
    if ([self getDocumentImage]) {
        image = [self getDocumentImage];
    } else {
        //         57629(IT106S) 45597（118）
        if (KK_BLEModel.bleAdvID == 57629 || KK_BLEModel.bleAdvID == 59677) {
            image = [UIImage imageNamed:@"银河240240"];
        } else if (KK_BLEModel.bleAdvID == 45597) {// 银
            image = [UIImage imageNamed:@"花瓣240240"];
        } else {
            image = [UIImage imageNamed:@"WechatIMG11"];
        }
        // 保存默认图片
//        [self saveImageDocuments:[UIImage imageCompressForSize:image targetSize:CGSizeMake(240, 240)]];
    }
    _backImageView       = [[UIImageView alloc]initWithFrame:CGRectMake((self.frame.size.width - 240) / 2, 0, 240, 240)];
    _backImageView.image = image;
    _sendImage222 = image;
//    _backImageView.contentMode =  UIViewContentModeScaleAspectFit;
    _backImageView.userInteractionEnabled = YES;
    if (SN_USER.screen_type == 0) {
        _backImageView.layer.borderWidth = 1.0;
        _backImageView.layer.borderColor = [[UIColor blackColor]colorWithAlphaComponent:0.3].CGColor;
    }
    [bgWhite2 addSubview:_backImageView];

    _screenView = [[FloatView alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
    [_backImageView addSubview:_screenView];

    // 显示步数
    UIView *stepBgView = [[UIView alloc] initWithFrame:CGRectMake(0, bgWhite2.bottom +23, screenWidth, 60)];
    stepBgView.backgroundColor = SNCOLORWHITE;
    [_bgView addSubview:stepBgView];

    UIImageView *stepImageView = [[UIImageView alloc] init];
    stepImageView.frame = CGRectMake(20, (stepBgView.height - 23)/2, 20, 23);
    stepImageView.image = [UIImage imageNamed:@"ghbz_icon_xsbs"];
    [stepBgView addSubview:stepImageView];

    //    UIImageView *stepShadowLine = [[UIImageView alloc] init];
    //    stepShadowLine.frame = SNFRAME(0, stepBgView.height - 2, HHHWIDTH, 2);
    //    stepShadowLine.image = [UIImage image:@"lineImage"];
    //    [stepBgView addSubview:stepShadowLine];

    UILabel *stepLabel = [[UILabel alloc] initWithFrame:CGRectMake(stepImageView.right+10, (stepBgView.height - 20)/2, 200, 20)];
    stepLabel.text          = HHH_Text(@"显示步数");
    stepLabel.textAlignment = NSTextAlignmentLeft;
    [stepBgView addSubview:stepLabel];

    _stepOpenSwitch = [[ZJSwitch alloc] initWithFrame:CGRectMake(screenWidth- 70, (stepBgView.height - 22)/2, 50, 22)];
    [_stepOpenSwitch addTarget:self action:@selector(clickedAction:) forControlEvents:UIControlEventValueChanged];
    _stepOpenSwitch.on  = YES;
    _stepOpenSwitch.tag = 666;
    [stepBgView addSubview:_stepOpenSwitch];

    // 文字颜色
    UIView *wordBgView = [[UIView alloc] initWithFrame:CGRectMake(0, stepBgView.bottom, screenWidth, 60)];
    wordBgView.backgroundColor = SNCOLORWHITE;
    [_bgView addSubview:wordBgView];

    UIImageView *wordImageView = [[UIImageView alloc] init];
    wordImageView.frame = CGRectMake(20, (wordBgView.height - 23)/2, 20, 23);
    wordImageView.image = [UIImage imageNamed:@"ghbz_icon_wzys"];
    [wordBgView addSubview:wordImageView];

    //    UIImageView *wordShadowLine = [[UIImageView alloc] init];
    //    wordShadowLine.frame = SNFRAME(0, wordBgView.height - 2, HHHWIDTH, 2);
    //    wordShadowLine.image = [UIImage image:@"lineImage"];
    //    [wordBgView addSubview:wordShadowLine];

    UILabel *wordLabel = [[UILabel alloc] initWithFrame:CGRectMake(wordImageView.right+10, (wordBgView.height - 20)/2, 80, 20)];
    wordLabel.text          = HHH_Text(@"文字颜色");
    wordLabel.textAlignment = NSTextAlignmentLeft;
    [wordBgView addSubview:wordLabel];

    NSArray *colors = @[SNRGB(255, 255, 255), SNRGB(254, 197, 198), SNRGB(253, 142, 143), SNRGB(253, 142, 35), SNRGB(93, 143, 195), SNRGB(0, 0, 0)];

    // 颜色选择
    for (int i = 0; i < 6; i++) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        [btn setFrame:CGRectMake(screenWidth - 20 - kScreenWidth / 12 * 6 + i * kScreenWidth / 12, (wordBgView.height -15) / 2, kScreenWidth / 12, 20)];
        btn.backgroundColor   = colors[i];
        btn.layer.borderColor = [UIColor blackColor].CGColor;
        btn.layer.borderWidth = 1.0;
        [btn addTarget:self action:@selector(btnClickAction:) forControlEvents:UIControlEventTouchUpInside];
        if (i == 3) {
            _currentSelectButton = btn;
            [_currentSelectButton setFrame:CGRectMake(_currentSelectButton.frame.origin.x, _currentSelectButton.frame.origin.y -10, kScreenWidth / 12, 40)];
            _screenView.stepImageView.tintColor   = _currentSelectButton.backgroundColor;//此时显示改变颜色后的图片
            _screenView.stepImageView.contentMode = UIViewContentModeScaleAspectFit;

            _screenView.timeImageView.tintColor   = _currentSelectButton.backgroundColor;//此时显示改变颜色后的图片
            _screenView.timeImageView.contentMode = UIViewContentModeScaleAspectFit;
        }
        [wordBgView addSubview:btn];
    }

    UIButton *cameraBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    cameraBtn.frame              = SNFRAME(17, wordBgView.bottom + 20, HHHWIDTH -34, 40);
    cameraBtn.backgroundColor    = SNCOLORBLACK;
    cameraBtn.layer.cornerRadius = 4.0;
    [cameraBtn setTitle:HHH_Text(@"拍照") forState:UIControlStateNormal];
    [cameraBtn setTitleColor:SNCOLORWHITE forState:UIControlStateNormal];
    [cameraBtn setTitleColor:SNCOLORGRAYLINE forState:UIControlStateHighlighted];
    [cameraBtn addTarget:self action:@selector(clickedAction:) forControlEvents:UIControlEventTouchUpInside];
    cameraBtn.tag = 100;
    [_bgView addSubview:cameraBtn];

    UIButton *photoAlbumBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    photoAlbumBtn.frame              = SNFRAME(17, cameraBtn.bottom + 20, HHHWIDTH -34, 40);
    photoAlbumBtn.backgroundColor    = SNCOLORBLACK;
    photoAlbumBtn.layer.cornerRadius = 4.0;
    [photoAlbumBtn setTitle:HHH_Text(@"从手机相册选择") forState:UIControlStateNormal];
    [photoAlbumBtn setTitleColor:SNCOLORWHITE forState:UIControlStateNormal];
    [photoAlbumBtn setTitleColor:SNCOLORGRAYLINE forState:UIControlStateHighlighted];
    [photoAlbumBtn addTarget:self action:@selector(clickedAction:) forControlEvents:UIControlEventTouchUpInside];
    photoAlbumBtn.tag = 200;
    [_bgView addSubview:photoAlbumBtn];
}

// 读取并存贮到相册
- (UIImage *)getDocumentImage {
    // 读取沙盒路径图片
    NSString *aPath3 = [NSString stringWithFormat:@"%@/Documents/%@.png", NSHomeDirectory(), KK_BLEModel.bleMAC];
    // 拿到沙盒路径图片
    UIImage *imgFromUrl3 = [[UIImage alloc]initWithContentsOfFile:aPath3];

    return imgFromUrl3;
}

//保存图片
- (void)saveImageDocuments:(UIImage *)image {
    //拿到图片
    UIImage  *imagesave   = image;
    NSString *path_sandox = NSHomeDirectory();
    //设置一个图片的存储路径
    NSString *imagePath = [path_sandox stringByAppendingString:[NSString stringWithFormat:@"/Documents/%@.png", KK_BLEModel.bleMAC]];

    //把图片直接保存到指定的路径（同时应该把图片的路径imagePath存起来，下次就可以直接用来取）
    [UIImagePNGRepresentation(imagesave) writeToFile:imagePath atomically:YES];
}

- (void)clickedAction:(id)sender {
    if (self.block) {
        self.block(sender);
    }
}

- (void)btnClickAction:(UIButton *)sender {
    [_currentSelectButton setFrame:CGRectMake(_currentSelectButton.frame.origin.x, _currentSelectButton.frame.origin.y + 10, kScreenWidth / 12, 20)];
    [sender setFrame:CGRectMake(sender.frame.origin.x, sender.frame.origin.y -10, kScreenWidth / 12, 40)];
    _currentSelectButton = sender;
    if (!self.screenView.stepImageView.hidden) {
        self.screenView.stepImageView.tintColor = sender.backgroundColor;
    }
    self.screenView.timeImageView.tintColor = sender.backgroundColor;
}

- (NSArray *)imageToTransparentArray:(UIImage *)image {
    NSMutableArray *arr = [NSMutableArray array];
    // 分配内存
    const int imageWidth   = image.size.width;
    const int imageHeight  = image.size.height;
    size_t    bytesPerRow  = imageWidth * 4;
    uint32_t  *rgbImageBuf = (uint32_t *)malloc(bytesPerRow * imageHeight);
    // 创建context
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef    context    = CGBitmapContextCreate(rgbImageBuf, imageWidth, imageHeight, 8, bytesPerRow, colorSpace,

                                                       kCGBitmapByteOrder32Little | kCGImageAlphaNoneSkipLast);

    CGContextDrawImage(context, CGRectMake(0, 0, imageWidth, imageHeight), image.CGImage);
    // 遍历像素
    int       pixelNum   = imageWidth * imageHeight;
    NSInteger blackcount = 0;
    NSInteger whitecount = 0;
    uint32_t  *pCurPtr   = rgbImageBuf;
    for (int i = 0; i < pixelNum; i++, pCurPtr++) {
        //接近粉色
        //将像素点转成子节数组来表示---第一个表示透明度即ARGB这种表示方式。ptr[0]:透明度,ptr[1]:R,ptr[2]:G,ptr[3]:B
        //分别取出RGB值后。进行判断需不需要设成透明。
        uint8_t *ptr = (uint8_t *)pCurPtr;
        // NSLog(@"1是%d,2是%d,3是%d",ptr[1],ptr[2],ptr[3]);
//            FF7A0D
        if (ptr[1] == 0 && ptr[2] == 0 && ptr[3] == 0) {
            [arr addObject:StrByInt(i)];
            blackcount++;
        }
    }

    CGContextRelease(context);
    CGColorSpaceRelease(colorSpace);
    return arr;
}

- (UIImage *)imageToTransparent:(UIImage *)image withChange:(NSArray *)array; {
    // 分配内存
    const int imageWidth   = image.size.width;
    const int imageHeight  = image.size.height;
    size_t    bytesPerRow  = imageWidth * 4;
    uint32_t  *rgbImageBuf = (uint32_t *)malloc(bytesPerRow * imageHeight);
    // 创建context
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef    context    = CGBitmapContextCreate(rgbImageBuf, imageWidth, imageHeight, 8, bytesPerRow, colorSpace,

                                                       kCGBitmapByteOrder32Little | kCGImageAlphaNoneSkipLast);

    CGContextDrawImage(context, CGRectMake(0, 0, imageWidth, imageHeight), image.CGImage);
    // 遍历像素
    int      pixelNum = imageWidth * imageHeight;
    uint32_t *pCurPtr = rgbImageBuf;
    for (int i = 0; i < pixelNum; i++, pCurPtr++) {
        //将像素点转成子节数组来表示---第一个表示透明度即ARGB这种表示方式。ptr[0]:透明度,ptr[1]:R,ptr[2]:G,ptr[3]:B
        //分别取出RGB值后。进行判断需不需要设成透明。
        uint8_t  *ptr    = (uint8_t *)pCurPtr;
        NSString *change = StrByInt(i);
        if ([array containsObject:change]) {
            ptr[1] = 0x66;
            ptr[2] = 0x66;
            ptr[3] = 0x66;
            ptr[0] = 0;
        }
    }
    // 将内存转成image
    CGDataProviderRef dataProvider = CGDataProviderCreateWithData(NULL, rgbImageBuf, bytesPerRow * imageHeight, nil);
    CGImageRef        imageRef     = CGImageCreate(imageWidth, imageHeight, 8, 32, bytesPerRow, colorSpace,

                                                   kCGImageAlphaLast |kCGBitmapByteOrder32Little, dataProvider,

                                                   NULL, true, kCGRenderingIntentDefault);


    CGDataProviderRelease(dataProvider);
    UIImage *resultUIImage = [UIImage imageWithCGImage:imageRef];
    // 释放
    CGImageRelease(imageRef);
    CGContextRelease(context);
    CGColorSpaceRelease(colorSpace);
    return resultUIImage;
}

@end
